package com.kingyun.gpsinspection.purificationservice.common.poi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.date.DateUtil;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by yangcs on 2017/3/17.
 */
public class ReportUtil {

    public static JSONArray getDataArr(int startHour, int cycleInterval, int reportType, Date date){
        JSONArray jsonArray = new JSONArray();
        JSONObject obj;
        // 日报表
        if( reportType == 1 || reportType == 3 ){
            for( int i=startHour;i<startHour+24;i=(i+cycleInterval) ){
                obj = new JSONObject();
                if( i>= 24 ){
                    obj.put("date",(i-24)+":00");// 页面显示
                    obj.put("hour",i-24<10?"0"+(i-24):i-24);//数据库查询对应TIMESTR字段
                }else{
                    obj.put("date",i+":00");// 页面显示
                    obj.put("hour",i<10?"0"+i:i);//数据库查询对应TIMESTR字段
                }
                obj.put("day", DateUtil.DateToString(date,"yyyyMMdd"));//数据库查询对应DATASTR字段
                jsonArray.add(obj);
            }
        }else{
            // 月报表
            // 转换日期为所在月的第一天
            date = getFirstDay(date);
            // 日期所在月有多少天
            int days = getDaysByMouth(date);
            Date rowDate;
            for( int i=1;i<=days;i++ ){
                obj = new JSONObject();
                rowDate = DateUtil.addDay(date,(i-1));
                obj.put("date",DateUtil.DateToString(rowDate,"yyyy-MM-dd")); // 页面显示
                obj.put("day",DateUtil.DateToString(rowDate,"yyyyMMdd"));
                obj.put("hour",0);
                jsonArray.add(obj);
            }
        }
        return jsonArray;
    }

    // 获取指定日期月份有多少天
    private static int getDaysByMouth(Date date){
        int year = DateUtil.getYear(date);
        int mouth = DateUtil.getMonth(date)-1;
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year); // 2010年
        c.set(Calendar.MONTH, mouth); // 6 月
        return c.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    // 获取指定日期所在月的第一天
    private static Date getFirstDay(Date date){
        int year = DateUtil.getYear(date);
        int mouth = DateUtil.getMonth(date)-1;
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, mouth);
        //设置日历中月份的第1天
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return cal.getTime();
    }

}
